<script>
import { del, fetchList, getOptionOfScale, getOptionOfType, getOptionOfUser, insert, update } from '@/api/company'
import { getToken } from '@/utils/auth'

export default {
  data() {
    return {
      searchContent: '',
      page: 1,
      pageSize: 20,
      pageTotal: 0,
      companyList: [],
      companyInfo: {
        companyPk: '',
        name: '',
        address: '',
        introduce: '',
        benefit: '',
        scaleFk: '1',
        typeFk: '1',
        img: '',
        userFk: '',
        companyPeople: 0,
        state: '0',
        authImg: '',
        authText: ''
      },
      isShow: false,
      formLabelWidth: '80px',
      scaleOptions: [],
      typeOptions: [],
      userOptions: [],
      authStatus: [
        {
          label: '认证成功',
          value: '2'
        },
        {
          label: '正在审核',
          value: '1'
        },
        {
          label: '没有认证',
          value: '0'
        },
        {
          label: '认证失败',
          value: '-1'
        }
      ],
      logoFiles: [],
      authImgFiles: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  created() {
    this.getScaleType()
    this.getTypeOptions()
    this.getUserOptions()
  },
  mounted() {
    this.getData()
  },
  methods: {
    getToken,
    getData() {
      fetchList(this.page, this.pageSize, this.searchContent)
        .then(res => {
          // console.log(res)
          const msg = res.message
          this.companyList = msg.list
          this.pageTotal = msg.total
        })
    },
    getScaleType() {
      getOptionOfScale()
        .then(res => {
          // console.log(res)
          this.scaleOptions = res.message
        })
    },
    getTypeOptions() {
      getOptionOfType()
        .then(res => {
          // console.log(res)
          this.typeOptions = res.message
        })
    },
    getUserOptions() {
      getOptionOfUser()
        .then(res => {
          // console.log(res)
          this.userOptions = res.message
        })
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.page = val
    },
    reset() {
      this.searchContent = ''
      this.page = 1
      this.pageSize = 20
      this.pageTotal = 0
      this.getData()
    },
    submitInfo() {
      let arrAuthImg = []
      this.authImgFiles.forEach(el => {
        try {
          arrAuthImg.push(el.response.message)
        } catch (e) {
          console.log(e)
        }
      })
      let data = null
      data = { ...this.companyInfo }
      data.authImg = JSON.stringify(arrAuthImg)
      data.scaleFk = data.scaleFk !== '' ? parseInt(data.scaleFk) : ''
      data.typeFk = data.typeFk !== '' ? parseInt(data.typeFk) : ''
      data.state = data.state !== '' ? parseInt(data.state) : ''
      // console.log(data)
      if (this.companyInfo.companyPk === '') {
        // 进行新增操作
        insert(data)
          .then(res => {
            // console.log(res)
            if (res.success) {
              this.$message({
                type: 'success',
                message: '新增成功'
              })
              this.getData()
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
      } else {
        // 进行更改操作
        update(data)
          .then(res => {
            // console.log(res)
            if (res.success) {
              this.$message({
                type: 'success',
                message: '更新成功'
              })
              this.getData()
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
      }
      this.isShow = false
    },
    created() {
      this.resetFormData()
      this.isShow = true
    },
    // 重置表单数据
    resetFormData() {
      this.companyInfo = {
        companyPk: '',
        name: '',
        address: '',
        introduce: '',
        benefit: '',
        scaleFk: '1',
        typeFk: '1',
        img: '',
        userFk: '',
        companyPeople: 0,
        state: '0',
        authImg: '',
        authText: ''
      }
      this.logoFiles = []
      this.authImgFiles = []
    },
    handleRemoveLogo(file, fileList) {
      // console.log(file, fileList)
    },
    handleSuccessLogo(response, file, fileList) {
      // console.log(response)
      const url = response.message
      this.companyInfo.img = url
      this.logoFiles = [{
        name: file.name,
        url: url
      }]
    },
    handleSuccessAuthImg(response, file, fileList) {
      // console.log(response)
      // console.log(fileList)
      this.authImgFiles = fileList
    },
    handleError(err, file, fileList) {
      console.log(err)
      this.$message({
        message: file.name + '上传失败',
        type: 'error'
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemoveAuthImg(file, fileList) {
      // console.log(file, fileList)
    },
    handlePictureCardPreviewImg(url) {
      this.dialogImageUrl = url
      this.dialogVisible = true
    },
    editCompanyInfo(row) {
      this.resetFormData()
      // console.log(row)
      let data = row
      data.scaleFk = `${data.scaleFk}`
      data.typeFk = `${data.typeFk}`
      data.state = `${data.state}`
      if (data.img !== '') {
        this.logoFiles.push({
          name: 'logo',
          url: data.img
        })
      }
      if (data.authImg && data.authImg !== '' && data.authImg !== '[]') {
        const arr = JSON.parse(data.authImg)
        arr.forEach(el => {
          this.authImgFiles.push({
            name: 'auth',
            url: el,
            response: {
              message: el
            }
          })
        })
      }
      this.companyInfo = data
      this.isShow = true
    },
    delCompanyInfo(row) {
      this.$confirm('此操作将永久删除该公司，以及相关岗位, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(row.companyPk)
          .then(res => {
            // console.log(res)
            if (res.success) {
              this.$message({
                type: 'success',
                message: '删除成功'
              })
              this.getData()
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<template>
  <div>
    <el-dialog :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" alt="" width="100%">
    </el-dialog>
    <el-dialog :visible.sync="isShow" title="公司信息">
      <el-form :model="companyInfo">
        <el-row>
          <el-col :span="12">
            <el-form-item :label-width="formLabelWidth" label="公司名称">
              <el-input v-model="companyInfo.name" autocomplete="off" placeholder="请输入公司名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label-width="formLabelWidth" label="公司人数">
              <el-input v-model="companyInfo.companyPeople" placeholder="请输入公司人数" type="number"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item :label-width="formLabelWidth" label="公司地址">
          <el-input v-model="companyInfo.address" autocomplete="off" placeholder="请输入公司地址"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="公司简介">
          <el-input v-model="companyInfo.introduce" autocomplete="off" placeholder="请输入公司简介" type="textarea"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="公司福利">
          <el-input v-model="companyInfo.benefit" autocomplete="off" placeholder="请输入公司福利" type="textarea"/>
        </el-form-item>

        <el-row>
          <el-col :span="8">
            <el-form-item :label-width="formLabelWidth" label="经营规模">
              <el-select v-model="companyInfo.scaleFk" filterable placeholder="请选择公司经营规模">
                <el-option
                  v-for="item in scaleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label-width="formLabelWidth" label="经营模式">
              <el-select
                v-model="companyInfo.typeFk"
                filterable
                placeholder="请选择公司经营模式"
              >
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label-width="formLabelWidth" label="审核状态">
              <el-select v-model="companyInfo.state" placeholder="请选择公司审核状态">
                <el-option v-for="item in authStatus" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label-width="formLabelWidth" label="归属人">
              <el-select v-model="companyInfo.userFk" filterable placeholder="请选择公司归属人">
                <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item :label-width="formLabelWidth" label="Logo">
          <el-upload
            :file-list="logoFiles"
            :headers="{
              token:getToken()
            }"
            :limit="1"
            :on-error="handleError"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemoveLogo"
            :on-success="handleSuccessLogo"
            action="/api/upload/img"
            list-type="picture-card"
          >
            <i class="el-icon-plus"/>
          </el-upload>
        </el-form-item>

        <el-form-item :label-width="formLabelWidth" label="审核材料">
          <el-upload
            :file-list="authImgFiles"
            :headers="{
              token:getToken()
            }"
            :limit="9"
            :on-error="handleError"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemoveAuthImg"
            :on-success="handleSuccessAuthImg"
            action="/api/upload/img"
            list-type="picture-card"
            multiple
          >
            <i class="el-icon-plus"/>
          </el-upload>
        </el-form-item>


        <el-row>
          <el-col :span="24">
            <el-form-item :label-width="formLabelWidth" label="审核备注">
              <el-input v-model="companyInfo.authText" autocomplete="off" placeholder="请输入审核备注" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="submitInfo">确 定</el-button>
      </div>
    </el-dialog>
    <div class="d-flex ai-center jc-end">
      <el-input
        v-model="searchContent"
        placeholder="请输入公司名称"
        prefix-icon="el-icon-search"
        style="max-width: 220px;margin-right: 10px;"
      />
      <el-button type="primary" @click="getData">搜索</el-button>
      <el-button type="primary" @click="reset">重置</el-button>
      <el-button type="primary" @click="created">新增</el-button>
    </div>

    <el-table :data="companyList" height="75vh" style="width: 100%;margin-top: 20px">
      <el-table-column type="index" width="50"/>
      <el-table-column label="公司名称" prop="name" width="180"/>
      <el-table-column label="Logo" width="120">
        <template slot-scope="scope">
          <div @click="handlePictureCardPreviewImg(scope.row.img)">
            <el-avatar :src="scope.row.img" shape="square" size="medium"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="地址" prop="address" width="220"/>
      <el-table-column label="福利" prop="benefit" width="220"/>
      <el-table-column label="简介" prop="introduce" width="220"/>
      <el-table-column label="规模" prop="scale" width="120"/>
      <el-table-column label="企业类型" prop="type" width="120"/>
      <el-table-column label="认证状态" width="120">
        <template slot-scope="scope">
          <div>
            {{
              scope.row.state === 1 || scope.row.state === '1' ? '正在认证' :
                scope.row.state === 2 || scope.row.state === '2' ? '认证成功' :
                  scope.row.state === 0 || scope.row.state === '0' ? '没有认证' : '认证失败'
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <div class="d-flex flex-wrap">
            <el-button type="primary" @click="editCompanyInfo(scope.row)">编辑</el-button>
            <el-button type="danger" @click="delCompanyInfo(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="d-flex jc-end">
      <el-pagination
        :current-page="page"
        :page-size="pageSize"
        :page-sizes="[20, 50, 100, 200]"
        :total="pageTotal"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>

</style>
